package cn.yunyichina.utils.convert;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * Map工具类
 *
 * @author zhangkewen
 */
public class MapUtils {

    /**
     * 排序后组合字符串
     *
     * @param data
     * @return
     */
    public static String coverMap2SignString(Map<String, String> data) {
        TreeMap<String, String> tree = new TreeMap<>();
        Iterator<Entry<String, String>> it = data.entrySet().iterator();

        while (it.hasNext()) {
            Entry<String, String> en = it.next();
            if ("sign".equals(en.getKey().trim()) || "request_type".equals(en.getKey().trim())) {
                continue;
            }
            tree.put(en.getKey(), en.getValue());
        }

        it = tree.entrySet().iterator();
        StringBuffer sf = new StringBuffer();

        while (it.hasNext()) {
            Entry<String, String> en = it.next();
            sf.append(en.getValue());
        }

        return sf.toString();
    }

    public static String convertMap2String(Map<String, String> data) {
        TreeMap<String, String> tree = new TreeMap<>();
        Iterator<Entry<String, String>> it = data.entrySet().iterator();

        while (it.hasNext()) {
            Entry<String, String> en = it.next();
            tree.put(en.getKey(), en.getValue());
        }

        it = tree.entrySet().iterator();
        StringBuffer sf = new StringBuffer();

        while (it.hasNext()) {
            Entry<String, String> en = it.next();
            sf.append(en.getKey() + "=" + en.getValue() + "&");
        }

        String params = sf.toString();
        params = params.substring(0, params.length() - 1);

        return params;
    }

    public static String convertMap2UrlEncodeString(Map<String, String> data, String charset) {
        TreeMap<String, String> tree = new TreeMap<>();
        Iterator<Entry<String, String>> it = data.entrySet().iterator();

        while (it.hasNext()) {
            Entry<String, String> en = it.next();
            tree.put(en.getKey(), en.getValue());
        }

        it = tree.entrySet().iterator();
        StringBuffer sf = new StringBuffer();

        while (it.hasNext()) {
            Entry<String, String> en = it.next();
            try {
                sf.append(en.getKey() + "=" + URLEncoder.encode(en.getValue(), charset) + "&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        String params = sf.toString();
        params = params.substring(0, params.length() - 1);

        return params;
    }

}
